package com.atguigu.tingshu.order.context;

import com.atguigu.tingshu.order.strategy.OrderTradeStrategy;
import com.atguigu.tingshu.order.strategy.OrderTradeStrategy;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class OrderTradeStrategyContext implements ApplicationContextAware {

    //定义一个成员变量,用来存储OrderTradeStrategyContext对象的实现类对象
    private static final Map<String , OrderTradeStrategy> ORDER_TRADE_STRATEGY_MAP = new ConcurrentHashMap<String , OrderTradeStrategy>();

    //根据付款项目类型，获取对应的策略实现类对象
    public static OrderTradeStrategy getOrderTradeStrategy(String itemType){
        return ORDER_TRADE_STRATEGY_MAP.get(itemType) ;

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, OrderTradeStrategy> beansOfType = applicationContext.getBeansOfType(OrderTradeStrategy.class);

        beansOfType.values().forEach(OrderTradeStrategy -> {
            String itemType = OrderTradeStrategy.getItemType();//获取付款项目类型
            ORDER_TRADE_STRATEGY_MAP.put(itemType,OrderTradeStrategy);
        });

    }
}
